﻿
namespace ApiTemplate.Common
{
    public class EmailHelper
    {
        /// <summary>
        /// 发送邮件
        /// </summary>
        public void SendEmail(EmailInput input)
        {
            string passwordKey = "gfn******qVx";
            string sendAddress = "****@163.com";
            //创建一个邮件服务器类  
            using SmtpClient myclient = new()
            {
                Host = "smtp.163.com",
                Port = 25,
                EnableSsl = true,
                UseDefaultCredentials = false,
                //验证登录  
                Credentials = new NetworkCredential(sendAddress, passwordKey)//"@"输入有效的邮箱名, "*"输入有效的密码（此密码就是注册邮箱服务器是发送短信后给的密码）
            };
            //声明一个Mail对象     
            using MailMessage mymail = new();
            if (input.FilePath != null)
            {
                foreach (string item in input.FilePath)
                {
                    mymail.Attachments.Add(new Attachment(item));  //为该电子邮件添加附件   附件的路径   
                }
            }

            //发件人地址 
            //如是自己，在此输入自己的邮箱   
            mymail.From = new MailAddress(sendAddress, "****");
            //收件人地址
            foreach (string item in input.Address)
            {
                mymail.To.Add(new MailAddress(item));
            }
            //邮件主题
            mymail.Subject = input.Subject;
            //邮件标题编码
            mymail.SubjectEncoding = Encoding.UTF8;
            //发送邮件的内容
            mymail.Body = input.Body;
            //邮件内容编码
            mymail.BodyEncoding = Encoding.UTF8;
            //是否是HTML邮件
            mymail.IsBodyHtml = false;
            //邮件优先级
            mymail.Priority = MailPriority.Normal;
            myclient.Send(mymail);
        }
    }

    /// <summary>
    /// 邮箱的输入对象
    /// </summary>
    public class EmailInput
    {
        /// <summary>
        /// 接收邮箱
        /// </summary>
        public List<string> Address { get; set; }

        /// <summary>
        /// 发送主题
        /// </summary>
        public string Subject { get; set; }

        /// <summary>
        /// 正文内容
        /// </summary>
        public string Body { get; set; }

        /// <summary>
        /// 附件的物理路径
        /// </summary>
        public List<string> FilePath { get; set; }
    }
}
